<template>
	<div>
		<div v-if="item">
			<ListItem :v="item"></ListItem>
			<ul class="comment-list">
				<li v-for="v in item.comment" :key="v.id">
					<h2>
						<div>
							<img :src="v.avator" alt="">
							<b>{{ v.nickname }}</b>
						</div>
						<small>{{ v.createTime }}</small>
					</h2>
					<p>{{ v.content }}</p>
				</li>
			</ul>

			<div>
				<h2>添加评论</h2>
				<van-field type="textarea" v-model="content" placeholder="请输入内容" maxlength="1000" show-word-limit/>
				<van-button type="primary" block v-if="isLogin" @click="handleAddCommment">添加评论</van-button>
				<van-button type="primary" block v-else @click="$router.push('/login')">未登录， 先去登录！</van-button>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { defineProps, onMounted } from 'vue'
import { ref } from 'vue'
import { HomeListState, RootState } from '@/store'
import { Notify } from 'vant'
import { useRouter } from 'vue-router'
import axios from 'axios'
import ListItem from '@/components/ListItem/ListItem.vue'
import { useStore } from 'vuex'
import { computed } from '@vue/reactivity'
const store = useStore<RootState>()
const router = useRouter()
const props = defineProps(['id'])
const item = ref<HomeListState | null>(null)

const isLogin = computed(() => store.state.user.isLogin)
const nickname = computed(() => store.state.user.nickname)
const avator = computed(() => store.state.user.avator)
const content = ref('')

const fetchData = async (id) => {
	const resp = await axios.get('/api/detail', { params: { id } });
	const { code, data, message } = resp.data;
	if (code === 200) {
		item.value = data;
		store.commit('addHistoryList', item.value)
	} else {
		Notify({ type: 'danger', message, onClose() { router.back() } })
	}
}

const handleAddCommment = async () => {
	const resp = await axios.post('/api/comment/add', { 
		id: props.id,  
		comment: {
			nickname: nickname.value,
			avator: avator.value,
			content: content.value
		}
	});
	Notify({ type: 'success', message: '添加评论成功！' })
	fetchData(props.id)
}
onMounted(() => fetchData(props.id))


</script>


<style scoped lang="scss">
.comment-list {
	li {
		padding: 10px;

		h2 {
			display: flex;
			justify-content: space-between;

			img {
				height: 20px;
				border-radius: 50%;
				margin-right: 10px;
			}
		}

		border-bottom: 1px solid #ccc;
	}
}
</style>